from django.http import JsonResponse
from common.models import Order, OrderMedicine
from lib.handler import dispatcherBase
from django.db.models import F, Q
from django.db import transaction
from django.core.paginator import Paginator
import traceback
import json


# 以下为api接口1.2
def list_order(request):
    # 读取订单表并添加其他表的相关数据
    orders = Order.objects.annotate(
        customer_name=F('customer__name'),
        ).values()
    pagesize = request.params['pagesize']
    pagenum = request.params['pagenum']
    keywords = request.params.get('keywords')
    if keywords:
        keywords_list = keywords.split()
        query = Q()
        for k in keywords_list:
            query |= Q(name__contains=k)
        orders = orders.filter(query)
    pgnt = Paginator(orders, pagesize)
    page = pgnt.get_page(pagenum)
    retlist = list(page) # QuerySet值转列表
    return JsonResponse({'ret': 0, 'retlist': retlist, 'total': pgnt.count})

def add_order(request):
    data = request.params['data']
    medicinelist = data['medicinelist']
    # 测试修改展示形式
    # medicinelist2 = []
    # for medicine in medicinelist:
    #     medicinelist2.append(f"{medicine['name']}*{medicine['amount']}")

    # 事务操作
    with transaction.atomic():
        order = Order.objects.create(
            name = data['name'],
            customer_id = data['customerid'],
            # 写入json格式的药品数据到 medicinelist 字段中
            medicinelist = json.dumps(medicinelist, ensure_ascii=False),
            # 测试修改展示形式
            # medicinelist = '、'.join(medicinelist2),
        )
        batch = [OrderMedicine(
            order_id=order.id,
            medicine_id=medicine['id'],
            amount = medicine['amount']
            ) for medicine in medicinelist]
        OrderMedicine.objects.bulk_create(batch)

    return JsonResponse({'ret': 0, 'id': order.id})

def delete_order(request):
    id = request.params['id']
    try:
        order = Order.objects.get(id=id)
        with transaction.atomic():
            OrderMedicine.objects.filter(order_id=id).delete()
            order.delete()
        return JsonResponse({'ret': 0, 'id': id})

    except Order.DoesNotExist:
        return JsonResponse({'ret': 1, 'msg': f'id 为{id}的订单不存在'})
    except:
        err = traceback.format_exc()
        return JsonResponse({'ret': 1, 'msg': err})


action_handler_dict = {
    'list_order': list_order,
    'add_order': add_order,
    'delete_order': delete_order,
}

def dispatcher(request):
    return dispatcherBase(request, action_handler_dict)
